# coding:utf-8
# py2
from __future__ import print_function
from __future__ import print_function
import commands
import os
import sys

from crawler.danmaku_density import convert_cid, count_ep_dense
from crawler.video_download import get_download_list, download_mp4

sys.path.append('/Users/lingzhengxin/workspace/python/Gunbaster')
sys.path.append('../..')
# season批量ep
if __name__ == '__main__':

    season_ids = [27049]
    gif_LW = '640x400'
    root_path = '/Users/lingzhengxin/Documents/season_gif/'
    filtered_key_word = ['完结', '撒花', '诈尸', '有生之年', '咚']
    boost_key_word = ['awsl']
    for season_id in season_ids:
        base_path = root_path + str(season_id)
        if not os.path.exists(base_path):
            os.makedirs(base_path)
        # seasonid = 123
        # epid = 259772
        # epid = 267858
        density_seconds = 5
        # epid转cid
        eps = convert_cid(season_id=season_id)
        for ep in eps:
            # 调用弹幕列表接口计算n秒内的最高弹幕密度
            try:
                ffmpeg_param = count_ep_dense(ep['cid'], density_seconds, ep['badge'], filtered_key_word)
            except:
                continue

            # 根据cid下载视频
            name = str(ep['index'])
            vedio_path = base_path + '/%s.mp4' % name
            result = get_download_list(ep['cid'])
            # 取下载清晰度最高的mp4视频的url地址
            largest_format_index = 0
            index = 0
            for info in result[u'info']:
                if info[u'format'] > largest_format_index:
                    largest_format_index = index
                index += 1
            download_url = result[u'info'][largest_format_index][u'url']
            download_mp4(name, download_url, vedio_path)
            # 转制gif
            shell_command = 'ffmpeg -i %s %s -s %s -pix_fmt rgb24 %s -y' % (
                vedio_path, ffmpeg_param, gif_LW, vedio_path.replace('.mp4', '.gif'))
            (status, output) = commands.getstatusoutput(shell_command)
            print(status, output)
            shell_command = 'convert %s -fuzz %s -layers Optimize %s' % (
                vedio_path.replace('.mp4', '.gif'), '15%', vedio_path.replace('.mp4', 'fuzz.gif'))
            (status, output) = commands.getstatusoutput(shell_command)
            print(status, output)
